package com.cpointerz.jgtd.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * CorsFilter
 * 解决前后端分离架构的CORS问题
 */

@Component
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 把ServletRequest和ServletResponse转换为HttpServletRequest和HttpServletResponse以进行header相关操作
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        // 添加CORS相关响应头
        resp.setHeader("Access-Control-Allow-Credentials", "true"); //允许携带Cookie
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin")); //允许当前Origin
        resp.setHeader("Access-Control-Allow-Methods", "*"); //允许所有方法
        resp.setHeader("Access-Control-Allow-Headers", "*"); //允许所有自定义header
        // 处理OPTIONS请求（见CORS协议）
        if (req.getMethod().equals("OPTIONS")) {
            servletResponse.getWriter().println("ok");
            return;
        }
        // 执行其他过滤器
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

